package com.mybatisplugin.springboot.controller;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.mybatisplugin.springboot.model.User;
import com.mybatisplugin.springboot.service.CityService;
import com.mybatisplugin.springboot.service.UserService;

@RestController
@RequestMapping("/index")
public class IndexController {
	 @Autowired
	 private CityService cityService;
	 @Autowired
	 private UserService userService;
	
	@RequestMapping("/index")
	public ModelAndView index(){
		ModelAndView modelAndView = new ModelAndView("index");
//        userService.testCache1("1");
//        userService.testCache1("1");
		return modelAndView;
	}
	
    @RequestMapping("/login")
    public ModelAndView login() {
    	Subject subject = SecurityUtils.getSubject();
    	if(null != subject){
    		subject.logout();
    		
    	}
    	ModelAndView modelAndView = new ModelAndView("login");
		return modelAndView;
    }
    
    @RequestMapping("/loginUser")
    public ModelAndView loginUser(String username,String password,HttpSession session) {
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(usernamePasswordToken);   //完成登录
            User user=(User) subject.getPrincipal();
            session.setAttribute("user", user);
            return new ModelAndView("redirect:/cities/cities1");
        } catch(Exception e) {
        	ModelAndView modelAndView = new ModelAndView("login");
        	return modelAndView;
        }
        
    }
    
    @RequestMapping("/logOut")
    public ModelAndView logOut(HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
//	        session.removeAttribute("user");
        ModelAndView modelAndView = new ModelAndView("login");
		return modelAndView;
    }

}
